package bkhech.generator.mybatis.core;

import bkhech.generator.mybatis.domian.Generator;
import bkhech.generator.mybatis.domian.MyGenConfig;
import bkhech.generator.mybatis.util.YamlUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * GenConfig Loader
 *
 * @author guowm
 * @date 2022/8/10
 */
public final class GenConfigLoader {
    private static final Map<String, MyGenConfig> CONFIG = new HashMap<>(16);
    private static MyGenConfig enabledMyGenConfig;

    private GenConfigLoader() {
    }

    static {
        try {
            final Generator generator = YamlUtil.parse();
            final List<MyGenConfig> myGenConfigList = generator.getGenerator();
            final long count = myGenConfigList.stream().filter(MyGenConfig::isEnable).count();
            if (count != 1) {
                throw new RuntimeException("支持仅一个类型[enable]为true的配置");
            }
            myGenConfigList.forEach(item -> {
                CONFIG.put(item.getType(), item);
                if (item.isEnable()) {
                    enabledMyGenConfig = item;
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static MyGenConfig load() {
        final MyGenConfig myGenConfig = enabledMyGenConfig;
        if (Objects.nonNull(myGenConfig)) {
            return myGenConfig;
        }
        throw new RuntimeException("请先开启任何一个类型[type]的配置");
    }

}
